package org.asiainfo.auth.controller;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.temp.SaTempUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.asiainfo.auth.domain.vo.LoginTenantVo;
import org.asiainfo.auth.domain.vo.LoginVo;
import org.asiainfo.auth.domain.vo.TenantListVo;
import org.asiainfo.auth.service.IAuthStrategy;
import org.asiainfo.auth.service.ISysLoginService;
import org.asiainfo.common.core.domain.R;
import org.asiainfo.common.core.domain.model.LoginBody;
import org.asiainfo.common.core.utils.*;
import org.asiainfo.common.json.utils.JsonUtils;
import org.asiainfo.common.satoken.utils.LoginHelper;
import org.asiainfo.common.tenant.utils.TenantHelper;
import org.asiainfo.system.api.RemoteClientService;
import org.asiainfo.system.api.RemoteTenantService;
import org.asiainfo.system.api.RemoteUserService;
import org.asiainfo.system.api.domain.vo.RemoteClientVo;
import org.asiainfo.system.api.domain.vo.RemoteTenantVo;
import org.springframework.web.bind.annotation.*;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 认证服务
 *
 * @author dotor-ww
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class TokenController {

    private final ISysLoginService sysLoginService;

    @DubboReference
    private RemoteClientService remoteClientService;

    @DubboReference
    private RemoteTenantService remoteTenantService;

    @DubboReference
    private RemoteUserService remoteUserService;

    /**
     * 用户登录
     * 参数请查看LoginBody类和PasswordLoginBody类
     *
     * @param body 用户登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody String body) {
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        if (ObjectUtil.isNull(loginBody)) {
            return R.fail("登录参数不能为空");
        }
        ValidatorUtils.validate(loginBody);
        // 验证码二次校验
        sysLoginService.secondCheckCaptcha(loginBody.getId());
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        // 获取客户端
        RemoteClientVo clientVo = remoteClientService.queryByClientId(clientId);
        // 校验客户端
        sysLoginService.checkClientId(clientVo, grantType);
        // 返回Token
        return R.ok(IAuthStrategy.login(body, grantType, clientVo));
    }

    /**
     * 用户退出
     *
     * @param refreshToken 刷新令牌
     */
    @DeleteMapping("/logout/{refreshToken}")
    public R<Void> logout(@NotBlank(message = "刷新令牌不能为空") @PathVariable(value = "refreshToken") String refreshToken) {
        sysLoginService.logout(refreshToken);
        return R.ok();
    }

    /**
     * 刷新token
     *
     * @param refreshToken 刷新token
     */
    @GetMapping("/refreshToken/{refreshToken}")
    public R<Object> refreshToken(@NotBlank(message = "刷新令牌不能为空") @PathVariable(value = "refreshToken") String refreshToken) {
        Long userId = SaTempUtil.parseToken(refreshToken, Long.class);
        if (ObjectUtil.isNull(userId)) {
            return R.fail("刷新Token失败，此refreshToken无效");
        }
        String clientId = SaHolder.getRequest().getHeader("ClientId");
        RemoteClientVo clientVo = remoteClientService.queryByClientId(clientId);
        if (ObjectUtil.isNull(clientVo)) {
            return R.fail("刷新Token失败，客户端不存在");
        }
        String accessToken = sysLoginService.refreshToken(userId, TenantHelper.getTenantId(), clientVo);
        Map<String, Object> map = new HashMap<>();
        map.put("access_token", accessToken);
        return R.ok(map);
    }

    /**
     * 租户下拉
     *
     * @return 租户列表
     */
    @GetMapping("/tenant/list")
    public R<Object> tenantList(HttpServletRequest request) throws Exception {
        LoginTenantVo result = new LoginTenantVo();
        boolean enable = Convert.toBool(SpringUtils.getProperty("tenant.enabled"), false);
        result.setTenantEnabled(enable);
        // 如果未开启租户这直接返回
        if (!enable) {
            return R.ok(result);
        }
        List<RemoteTenantVo> tenantList = remoteTenantService.queryList();
        List<TenantListVo> voList = MapstructUtils.convert(tenantList, TenantListVo.class);
        try {
            // 如果只超管返回所有租户
            if (LoginHelper.isSuperAdmin()) {
                result.setVoList(voList);
                return R.ok(result);
            }
        } catch (NotLoginException ignored) {
        }
        // 获取域名
        String host;
        String referer = request.getHeader("referer");
        if (StringUtils.isNotBlank(referer)) {
            // 这里从referer中取值是为了本地使用hosts添加虚拟域名，方便本地环境调试
            host = referer.split("//")[1].split("/")[0];
        } else {
            host = new URL(request.getRequestURL().toString()).getHost();
        }
        // 根据域名进行筛选
        List<TenantListVo> list = StreamUtils.filter(voList, vo -> StringUtils.equals(vo.getTenantDomain(), host));
        result.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        return R.ok(result);
    }
}
